import { Injectable } from '@nestjs/common';
import { LoginAuthDto } from './dto/login.dto';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateAuthDto } from './dto/create-auth.dto';
import { CryptoService } from 'src/crypto/crypto.service';
import { resultUtil } from 'src/utils/result';
@Injectable()
export class AuthService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly jwtSevice: JwtService,
    private readonly cryptoService: CryptoService,
  ) {}

  /**
   * 登录
   */
  async login(loginAuthDto: LoginAuthDto) {
    //登录的时候去找数据库找这个用户
    const result = await this.prismaService.user.findFirst({
      where: {
        username: loginAuthDto.username,
      },
    });
    // 校验用户名是否正确
    if (loginAuthDto.username != result?.username) {
      return resultUtil('用户错误', '000001');
    }
    // 先对用户密码进行加密对比数据库里面的密码
    const validPassword = this.cryptoService.encrypto(loginAuthDto.password);
    if (validPassword !== result.password) {
      return resultUtil('密码错误', '000001');
    }
    //token加密
    return resultUtil(
      '',
      '000000',
      this.jwtSevice.sign({
        username: result.username,
        id: result.id,
        role: result.role
      }),
    );
  }
  /**
   * 注册
   */
  async register(createAuthDto: CreateAuthDto) {
    const res = await this.prismaService.user.findFirst({
      where: {
        username: createAuthDto.username,
      },
    });
    if (res) {
      return resultUtil('用户已存在', '000001');
    }
    try {
      await this.prismaService.user.create({
        data: {
          username: createAuthDto.username,
          role: createAuthDto.role,
          // 注册的时候密码加密
          password: this.cryptoService.encrypto(createAuthDto.password),
        },
      });
      return resultUtil('', '000000');
    } catch {
      return resultUtil('注册失败', '000001');
    }
  }

  async getRole(role: string) {
    return resultUtil('', '000000', role)
  }
}
